package cmd

import (
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/config"
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/logger"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/clickhouse"
	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/executor"

	"github.com/riete/errors"
	"github.com/spf13/cobra"
)

var (
	target        *clickhouse.Clickhouse
	failedSqlFile string
	runSqlFile    string
)

// runCmd represents the run command
var runCmd = &cobra.Command{
	Use:   "run",
	Short: "run sql",
	Long:  "",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		var err errors.Error
		target, err = clickhouse.New(config.Config.Target)
		if err != nil {
			logger.Fatal(err.Trace("连接目标数据库失败").Stack())
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		e := executor.New()
		e.RunSql(target, runSqlFile, false)
	},
}

// failedCmd represents the failed command
var failedCmd = &cobra.Command{
	Use:   "failed",
	Short: "run failed sql",
	Long:  "",
	Run: func(cmd *cobra.Command, args []string) {
		e := executor.New()
		e.RunSql(target, failedSqlFile, true)
	},
}

func init() {
	runCmd.AddCommand(failedCmd)
	runCmd.Flags().StringVarP(&runSqlFile, "sql-file", "s", "migration.sql", "/path/to/sql-file")
	failedCmd.Flags().StringVarP(&failedSqlFile, "sql-file", "s", "failed.sql", "/path/to/failed-sql-file")
}